<?php

namespace app\admin\controller\community\config;

use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\admin\model\community\config\Timezone as TimezoneModel;

/**
 * 时区代码配置管理
 *
 * @icon fa fa-clock-o
 */
class Timezone extends Backend
{
    /**
     * Timezone模型对象
     * @var \app\admin\model\community\config\Timezone
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new TimezoneModel();
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            $searchFields = ['id', 'code', 'name', 'remark'];
            $sortFields = ['id', 'code', 'name', 'community_id', 'publicwelfare_id', 'status', 'weigh', 'createtime', 'updatetime'];
            // 获取URL中传递的参数
            $community_id = $this->request->param('community_id', 0);
            $publicwelfare_id = $this->request->param('publicwelfare_id', 0);
            // 先执行重排code操作
            $this->autoGenerateCourseCode($community_id, $publicwelfare_id);

            list($where, $sort, $order, $offset, $limit) = $this->buildparams($sortFields, $searchFields);
            $where = [];
            // 如果有传递参数，则添加到查询条件中
            if ($community_id > 0) {
                $where['fa_community_timezone_config.community_id'] = $community_id;
            }
            if ($publicwelfare_id > 0) {
                $where['fa_community_timezone_config.publicwelfare_id'] = $publicwelfare_id;
            }

            // 使用数字填充的方式对code进行排序
            $sort = 'tz.id';
            $order = 'asc';
            
            // 获取所有数据
            $list = $this->model
                ->alias('tz')
                ->join('fa_community c', 'tz.community_id = c.id')
                ->join('fa_community_publicwelfare p', 'tz.publicwelfare_id = p.id')
                ->where($where)
                ->field('tz.*, c.name as community_name, p.project_name as publicwelfare_name')
                ->order($sort, $order)
                ->paginate($limit);
                
            // 获取所有数据项
            $items = $list->items();
            
            // 自定义排序逻辑
            usort($items, function($a, $b) {
                // 从代码中提取数字部分
                $numA = (int)preg_replace('/[^0-9]/', '', $a['code']);
                $numB = (int)preg_replace('/[^0-9]/', '', $b['code']);
                return $numA - $numB;
            });
            // 统计每个月多少节课
            $data = Db::name('fa_community_timeslot_config')->where("publicwelfare_id",$publicwelfare_id)->select();
            $classInADay = 0;
            $inMonthdayArray=[];
            $days=0;
            foreach($data as $item) {
                if(!empty($item['day'])) {
                    $classInADay++;
                    $monthdayArray[] = explode(',', $item['day']);
                    $days+=count($monthdayArray);
                    foreach($monthdayArray as $monthday) {
                        if(!in_array($monthday, $inMonthdayArray)) {
                            $inMonthdayArray[] = $monthday;
                        }
                    }
                }
            }
            //$days= count($inMonthdayArray[0])*$classInADay;
            // 如果没有数据，使用默认值
            if($days == 0) {
                $days = 10;
            }
            //增加输出错误提示信息，如果课程数量$course_count*社区数量$community_count>当前设置的时期数量$timezone_count*当前设置的每天时段数量$timeslot_count，则提示错误，并计算需要增加时期的数量，并给出提示一值设置到几月为止
            $community_count = Db::name('fa_community_code_config')->where("publicwelfare_id",$publicwelfare_id)->count();
            $course_count = Db::name('fa_community_course_config')->where("publicwelfare_id",$publicwelfare_id)->count();
            $timezone_count = Db::name('fa_community_timezone_config')->where("publicwelfare_id",$publicwelfare_id)->count();
            $timeslot_count = Db::name('fa_community_timeslot_config')->where("publicwelfare_id",$publicwelfare_id)->count();

//            try {
//                $generateUrl = "https://".$_SERVER['HTTP_HOST'].'/course/schedule/generate';
//                // 使用cURL进行POST请求
//                $ch = curl_init();
//                curl_setopt($ch, CURLOPT_URL, $generateUrl);
//                curl_setopt($ch, CURLOPT_POST, 1);
//                curl_setopt($ch, CURLOPT_POSTFIELDS, ['publicwelfare_id' => $publicwelfare_id]);
//                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
//                $response = curl_exec($ch);
//                $result = json_decode($response, true);
//                curl_close($ch);
//
//                if (!isset($result['code']) || $result['code'] != 1) {
//                    throw new Exception('自动排课失败');
//                }
//            } catch (Exception $e) {
//                Log::error('自动排课失败: ' . $e->getMessage());
//            }

            $endTimezone = Db::name('fa_community_timezone_config')
                ->where("publicwelfare_id", $publicwelfare_id)
                ->order('id desc')
                ->value('name');

            $endYearMonths = Db::name('fa_course_schedule')
                ->where("publicwelfare_id", $publicwelfare_id)
                ->order('year desc,month desc')
                ->field("year,month")
                ->limit(1)
                ->select();
            $endYearMonth = !empty($endYearMonths) && isset($endYearMonths[0]) ? $endYearMonths[0]['year']."年".$endYearMonths[0]['month']."月" : '';
            $message="";

            // 假设 $endTimezone 也是 "年份年月份月" 格式
            // 将字符串转换为可比较的数值格式
            function convertYearMonthToComparable($yearMonthStr) {
                // 提取年份和月份
                preg_match('/(\d{4})年(\d{1,2})月/', $yearMonthStr, $matches);
                if (count($matches) >= 3) {
                    $year = intval($matches[1]);
                    $month = intval($matches[2]);
                    return $year * 100 + $month; // 如 202506
                }
                return 0;
            }

            $endTimezoneComparable = convertYearMonthToComparable($endTimezone);
            $endYearMonthComparable = convertYearMonthToComparable($endYearMonth);

            if($endTimezoneComparable < $endYearMonthComparable){
//                // 获取第一个时期的名称
//                $firstTimezone = Db::name('fa_community_timezone_config')
//                    ->where("publicwelfare_id", $publicwelfare_id)
//                    ->order('id asc')
//                    ->value('name');
//
//                // 如果没有找到时期，使用默认值
//                if (!$firstTimezone) {
//                    $firstTimezone = date('Y年m月');
//                }
                
//                // 计算需要的月份数
//                $countMonth = ceil($course_count*$community_count/($days*$community_count));
//
//                // 从第一个时期名称中提取年月信息
//                if (preg_match('/(\d{4})年(\d{1,2})月/', $firstTimezone, $matches)) {
//                    $year = intval($matches[1]);
//                    $month = intval($matches[2]);
//
//                    // 计算新的年月
//                    $newMonth = $month + $countMonth;
//                    $newYear = $year;
//
//                    // 处理月份超过12的情况
//                    while ($newMonth > 12) {
//                        $newMonth -= 12;
//                        $newYear++;
//                    }
//
//                    // 格式化新的年月字符串
//                    $newYearMonth = sprintf('%d年%02d月', $newYear, $newMonth);
//                } else {
//                    // 如果无法解析时期名称，使用当前时间计算
//                    $currentDate = new \DateTime();
//                    $currentDate->add(new \DateInterval('P' . $countMonth . 'M'));
//                    $newYearMonth = $currentDate->format('Y年m月');
//                }
                $message="当前设置的时期数量不足以支持所有的课程和社区，可以通过如下方式处理<br>1，在【时期代码设置】增加时期数量<br>2，在【课程代码设置】中减少课程和社区数量<br>3，在【时间关联配置】中增加每天的时段或每月的日期<p>如果不做处理，程序将自动延期直到{$endYearMonth}为止。";
            }
            $result = ['total' => $list->total(), 'rows' => $items,'message'=>$message];
            return json($result);
        }

        // 获取URL中传递的参数并传递给视图
        $community_id = $this->request->param('community_id', 0);
        $publicwelfare_id = $this->request->param('publicwelfare_id', 0);
        $this->view->assign('community_id', $community_id);
        $this->view->assign('publicwelfare_id', $publicwelfare_id);

        // 如果通过网址传入了community_id和publicwelfare_id，则设置一个标记，用于控制视图中的字段显示
        $simplifiedView = ($community_id > 0 || $publicwelfare_id > 0);
        $this->view->assign('simplifiedView', $simplifiedView);

        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }

                // 获取community_id和publicwelfare_id
                $community_id = $this->request->param('community_id', 0);
                $publicwelfare_id = $this->request->param('publicwelfare_id', 0);
                if (!isset($params['community_id']) && $community_id > 0) {
                    $params['community_id'] = $community_id;
                }
                if (!isset($params['publicwelfare_id']) && $publicwelfare_id > 0) {
                    $params['publicwelfare_id'] = $publicwelfare_id;
                }

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    // 这里需要对所有的满足条件的数值进行按照名称的排序顺序，重新更新code='时区1'、'时区2'、'时区3'...
                    $community_id = $this->request->param('community_id', 0);
                    $publicwelfare_id = $this->request->param('publicwelfare_id', 0);
                    $community_timezone_config = new TimezoneModel();
                    // 获取排序好的记录
                    $records = $community_timezone_config
                        ->where('community_id', $community_id)
                        ->where('publicwelfare_id', $publicwelfare_id)
                        ->order('name asc')
                        ->select();

                    // 逐条更新 code 字段
                    foreach ($records as $key => $record) {
                        $record->save(['code' => '时区' . ($key + 1)]);
                    }
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        // 获取社区列表
        $communityList = \app\admin\model\Community::where('status', 1)->column('name', 'id');
        $this->view->assign('communityList', $communityList);

        // 获取公益项目列表
        $publicwelfareList = \app\admin\model\community\Publicwelfare::where('status', 1)->column('project_name', 'id');
        $this->view->assign('publicwelfareList', $publicwelfareList);

        // 获取当前用户所属社区和URL参数
        $user = $this->auth->getUserInfo();
        $community_id = $this->request->param('community_id', $user['community_id'] ?? 0);
        $publicwelfare_id = $this->request->param('publicwelfare_id', 0);
        $this->view->assign('community_id', $community_id);
        $this->view->assign('publicwelfare_id', $publicwelfare_id);

        // 查询未被选取的时区列表
        $timezoneList = [];
        if ($community_id > 0 && $publicwelfare_id > 0) {
            // 查询已经配置的时区代码
            $existingNames = $this->model
                ->where('community_id', $community_id)
                ->where('publicwelfare_id', $publicwelfare_id)
                ->column('name');

            // 查询所有可用的时区代码
            $allTimezones = TimezoneModel::where('community_id', $community_id)
                ->where('publicwelfare_id', $publicwelfare_id)
                ->select();
            $timezoneList = [];
            // 过滤出未被选取的时区代码
            foreach ($allTimezones as $timezone) {
                $timezoneName = isset($timezone['timezone_name']) ? $timezone['timezone_name'] : $timezone['id'];
                if (!in_array($timezoneName, $existingNames)) {
                    $timezoneName = isset($timezone['timezone_name']) ? $timezone['timezone_name'] : ($timezone['timezone_name'] ?? 'Unknown');
                    $timezoneList[$timezoneName] = $timezoneName;
                }
            }
        }
        $this->view->assign('timezoneList', $timezoneList);

        // 如果通过网址传入了community_id和publicwelfare_id，则设置一个标记，用于控制视图中的字段显示
        $simplifiedView = ($community_id > 0 || $publicwelfare_id > 0);
        $this->view->assign('simplifiedView', $simplifiedView);

        // 自动生成时区代码
        $n = 1;
        $code = $this->generateUniqueCode('时区', $n, $community_id, $publicwelfare_id);
        $this->view->assign('code', $code);
        return $this->view->fetch();
    }

    protected function autoGenerateCourseCode($communityId, $publicwelfareId)
    {
        if (empty($communityId) || empty($publicwelfareId)) {
            return;
        }

        // 获取该项目的所有时区配置，按名称排序
        $existingRecords = $this->model
            ->where('community_id', $communityId)
            ->where('publicwelfare_id', $publicwelfareId)
            ->order('name asc')
            ->select();

        // 重新排序时区代码
        $index = 1;
        foreach ($existingRecords as $record) {
            // 更新为连续的时区代码
            $newCode = '时区' . $index;

            // 只有当代码不同时才更新，避免不必要的数据库操作
            if ($record['code'] != $newCode) {
                $this->model->where('id', $record['id'])->update([
                    'code' => $newCode,
                    'update_time' => time()
                ]);
            }

            $index++;
        }

        // 如果没有时区配置，则从课程表中自动生成
        if (count($existingRecords) == 0) {
            // 自动生成13个月，包括跨年的日期
            $months = [];
            $currentMonth = date('n'); // 从当前月开始
            $currentYear = date('Y');
            
            // 生成13个月的数据，从当前月开始
            for ($i = 0; $i < 13; $i++) {
                // 计算目标月份和年份
                $targetMonth = ($currentMonth + $i - 1) % 12 + 1; // 确保月份在 1-12 范围内
                
                // 计算年份，如果超过12月，则年份+1
                $targetYear = $currentYear;
                if ($currentMonth + $i > 12) {
                    $targetYear += floor(($currentMonth + $i - 1) / 12);
                }
                
                // 格式化月份为两位数
                $month = $targetMonth < 10 ? '0' . $targetMonth : $targetMonth;
                $courseName = $targetYear . '年' . $month . '月';
                
                $months[] = [
                    'course_name' => $courseName
                ];
            }

            // 为每个月份生成时区代码并插入记录
            $index = 1;
            foreach ($months as $month) {
                // 插入新记录
                $data = [
                    'community_id' => $communityId,
                    'publicwelfare_id' => $publicwelfareId,
                    'code' => '时区' . $index,
                    'name' => $month['course_name'],
                    'status' => 1,
                    'createtime' => time(),
                    'updatetime' => time()
                ];

                $this->model->insert($data);
                $index++;
            }
        }
    }

    /**
     * 生成唯一的 code
     * @param string $prefix 前缀，例如 "C"
     * @param int $startIndex 起始索引，例如 1
     * @param int $communityId 社区ID
     * @param int $publicwelfareId 公益项目ID
     * @return string 唯一的 code
     */
    protected function generateUniqueCode($prefix, $startIndex, $communityId, $publicwelfareId)
    {
        $index = $startIndex;
        while (true) {
            $code = $prefix . $index; // 生成 code，例如 C1, C2, C3...

            // 检查 code 是否已存在
            $exists = $this->model
                ->where('community_id', $communityId)
                ->where('publicwelfare_id', $publicwelfareId)
                ->where('code', $code)
                ->count();

            // 如果不存在，则返回该 code
            if (!$exists) {
                return $code;
            }

            // 如果存在，则 index 加 1，继续循环
            $index++;
        }
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                // 保证名称不可更改
                unset($params['name']);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                    // 这里需要对所有的满足条件的数值进行按照名称的排序顺序，重新更新code='时区1'、'时区2'、'时区3'...
                    $community_id = isset($params['community_id']) ? $params['community_id'] : $this->request->param('community_id', 0);
                    $publicwelfare_id = isset($params['publicwelfare_id']) ? $params['publicwelfare_id'] : $this->request->param('publicwelfare_id', 0);
                    $community_timezone_config = new TimezoneModel();
                    // 获取排序好的记录
                    $records = $community_timezone_config
                        ->where('community_id', $community_id)
                        ->where('publicwelfare_id', $publicwelfare_id)
                        ->order('name asc')
                        ->select();

                    // 逐条更新 code 字段
                    foreach ($records as $key => $record) {
                        $record->save(['code' => '时区' . ($key + 1)]);
                    }
                    $this->success();


                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        // 获取社区列表
        $communityList = \app\admin\model\Community::where('status', 1)->column('name', 'id');
        $this->view->assign('communityList', $communityList);

        // 获取公益项目列表
        $publicwelfareList = \app\admin\model\community\Publicwelfare::where('status', 1)->column('project_name', 'id');
        $this->view->assign('publicwelfareList', $publicwelfareList);

        // 获取URL参数和当前用户所属社区
        $user = $this->auth->getUserInfo();
        $community_id = $this->request->param('community_id', $user['community_id'] ?? 0);
        $publicwelfare_id = $this->request->param('publicwelfare_id', 0);
        $this->view->assign('community_id', $community_id);
        $this->view->assign('publicwelfare_id', $publicwelfare_id);

        // 查询未被选取的时区列表
        $timezoneList = [];
        if ($community_id > 0 && $publicwelfare_id > 0) {
            // 查询已经配置的时区代码
            $existingNames = $this->model
                ->where('community_id', $community_id)
                ->where('publicwelfare_id', $publicwelfare_id)
                ->column('name');

            // 查询所有可用的时区代码
            $allTimezones = TimezoneModel::where('community_id', $community_id)
                ->where('publicwelfare_id', $publicwelfare_id)
                ->select();
            $timezoneList = [];
            // 过滤出未被选取的时区代码和当前时区代码
            foreach ($allTimezones as $timezone) {
                $timezoneName = isset($timezone['timezone_name']) ? $timezone['timezone_name'] : $timezone['id'];
                if (!in_array($timezoneName, $existingNames) || $timezoneName == $row['name']) {
                    $timezoneName = isset($timezone['timezone_name']) ? $timezone['timezone_name'] : ($timezone['timezone_name'] ?? 'Unknown');
                    $timezoneList[$timezoneName] = $timezoneName;
                }
            }
        }
        $this->view->assign('timezoneList', $timezoneList);

        // 如果通过网址传入了community_id和publicwelfare_id，则设置一个标记，用于控制视图中的字段显示
        $simplifiedView = ($community_id > 0 || $publicwelfare_id > 0);
        $this->view->assign('simplifiedView', $simplifiedView);

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }

        try {
            // 获取要删除的记录，以便获取其community_id和publicwelfare_id
            $records = $this->model->where('id', 'in', $ids)->select();
            $communityPublicwelfarePairs = [];

            foreach ($records as $record) {
                $pair = $record['community_id'] . '-' . $record['publicwelfare_id'];
                if (!in_array($pair, $communityPublicwelfarePairs)) {
                    $communityPublicwelfarePairs[] = $pair;
                }
            }

            // 强制删除记录
            $result = $this->model->where('id', 'in', $ids)->delete();

            if ($result) {
                // 这里需要对所有的满足条件的数值进行按照名称的排序顺序，重新更新code='时区1'、'时区2'、'时区3'...
                $community_id = $this->request->param('community_id', 0);
                $publicwelfare_id = $this->request->param('publicwelfare_id', 0);
                $community_timezone_config = new TimezoneModel();
                // 获取排序好的记录
                $records = $community_timezone_config
                    ->where('community_id', $community_id)
                    ->where('publicwelfare_id', $publicwelfare_id)
                    ->order('name asc')
                    ->select();

                // 逐条更新 code 字段
                foreach ($records as $key => $record) {
                    $record->save(['code' => '时区' . ($key + 1)]);
                }


                // 使用FastAdmin框架标准的成功返回格式
                return json(['code' => 1, 'msg' => __('Delete successful')]);
            } else {
                $this->error(__('No rows were deleted'));
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
    }
}
